package cn.edu.hbpu.service.impl;

import cn.edu.hbpu.common.R;
import cn.edu.hbpu.entity.FirstCategory;
import cn.edu.hbpu.handler.CustomException;
import cn.edu.hbpu.mapper.FirstCategoryMapper;
import cn.edu.hbpu.service.FirstCategoryService;
import cn.edu.hbpu.utils.DateTimeFormat;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author lcy
 * @date 2022/8/16 18:34
 * @description
 */
@Service
public class FirstCategoryServiceImpl implements FirstCategoryService {

    @Autowired
    private FirstCategoryMapper firstCategoryMapper;

    @Override
    public R<String> deleteFirstCategory(String fId) {
        if (Objects.isNull(fId)) {
            throw new CustomException("请传入一级分类id");
        }
        // 1. 删除用户
        firstCategoryMapper.deleteById(fId);
        // 2. 返回结果
        return new R<>(HttpStatus.HTTP_OK, "删除一级分类成功");
    }

    @Override
    public R<Page<FirstCategory>> pagingQuery(String searchField, String searchText, String startDateTime, String endDateTime, int page, int pageSize) {
        // 1. 非空验证
        if (Objects.isNull(searchField) || Objects.isNull(searchText)) {
            throw new CustomException("请传入搜索字段或文本");
        }
        LocalDateTime start = null;
        LocalDateTime end = null;
        // 2. 将日期进行转换
        if (!Objects.isNull(startDateTime) && !Objects.isNull(endDateTime)) {
            start = DateTimeFormat.parseTimeToUtc(startDateTime);
            end = DateTimeFormat.parseTimeToUtc(endDateTime);
        }
        // 3. 将searchField转为下划线
        searchField = StringUtils.camelToUnderline(searchField);

        // 4. 创建Page对象
        Page<FirstCategory> pageInfo = new Page<>(page, pageSize);

        // 5. 创建查询构造器
        QueryWrapper<FirstCategory> queryWrapper = new QueryWrapper<>();

        // 6. 判断searchField的字段类型
        if (searchField.isEmpty()) {
            // 6.1 搜索字段为空时
            // 6.1.1 分页查询所有数据
            firstCategoryMapper.selectPage(pageInfo, null);
        } else if ("create_time".equals(searchField) || "update_time".equals(searchField)) {
            // 6.2 当搜索字段为创建时间和更新时间时
            queryWrapper.ge(searchField, start).le(searchField, end);
            firstCategoryMapper.selectPage(pageInfo, queryWrapper);
        } else {
            // 6.3 当搜索字段为其它字段时
            queryWrapper.like(searchField, searchText);
            firstCategoryMapper.selectPage(pageInfo, queryWrapper);
        }

        // 7. 返回结果
        return new R<>(HttpStatus.HTTP_OK, pageInfo);
    }

}
